package com.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.Exception.DishStatusException;
import com.reggie.dao.DishDao;
import com.reggie.dao.SetmealDao;
import com.reggie.dao.SetmealDishDao;
import com.reggie.dto.DishDto;
import com.reggie.pojo.Dish;
import com.reggie.pojo.Setmeal;
import com.reggie.pojo.SetmealDish;
import com.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishDao dao;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private SetmealDishDao setmealDishDao;

    @Override
    public Page<Dish> selectByPage(Integer page, Integer pageSize, String name) {
        Page<Dish> pages = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //按照更新时间进行升序排序
        lqw.orderByDesc(Dish::getUpdateTime);
        dao.selectPage(pages, lqw);
        return pages;
    }

    @Override
    public int save(DishDto dishDto) {
        return dao.insert(dishDto);
    }

    @Override
    public boolean updateStatusById(Integer status, Long... ids) {
        //在修改状态前先对这个菜品进行查询如果这个菜品是某一个套餐中的，就抛出异常
        for (Long id : ids) {

            if (status == 0) {
                List<SetmealDish> setmealDishes = setmealDishDao.selectByDishId(id);
                System.out.println(setmealDishes);
                setmealDishes.forEach((item) -> {
                    //每一个代表他的所在的一个套餐，如果所有套餐都是禁用就改变
                    Setmeal setmeal = setmealDao.selectById(item.getSetmealId());
                    if(setmeal.getStatus() == 1){
                        throw new DishStatusException("当前的菜品已经绑定了套餐了！请先禁用对应的套餐");
                    }
                });
                dao.updateStatusById(status, id);
            }else {
                dao.updateStatusById(status,id);
            }
        }
        return true;
    }

    @Override
    public int updateDish(Dish dish) {
        return dao.updateById(dish);
    }

    @Override
    public void deleteByIds(Long... ids) {
        dao.deleteBatchIds(Arrays.stream(ids).toList());
    }

    @Override
    public List<Dish> selectDishByCategoryId(Long id) {
        return dao.selectByCategoryId(id);
    }

    public Dish selectById(Long id) {
        return dao.selectById(id);
    }
}
